package com.nsy.ovulatorymonitor.domain;

import java.util.ArrayList;
import java.util.List;
import com.nsy.ovulatorymonitor.dummy.PeriodInfo;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.provider.BaseColumns;
import android.util.Log;

public final class PeridInfoContract {
	private Context _context = null;
	public PeridInfoContract(Context context){
		_context = context;
	}
	
	private String _LogTag = "PeriodInfo"; 
	
	public static abstract class PeridInfoEntry implements BaseColumns
	{
		public static final String TABLE_NAME = "PeriodInfo";         
		public static final String COLUMN_NAME_PERIOD_ID = "ID"; 
		public static final String COLUMN_NAME_PERIOD_NAME = "NAME";
		public static final String COLUMN_NAME_PERIOD_STARTDATE = "STARTDATE";	

	}
	
	
	public long AddNewPeriod(String name)
	{
		try
		{
			OvulatoryMonitorDbHelper mDbHelper = new OvulatoryMonitorDbHelper(_context);
			SQLiteDatabase db = mDbHelper.getWritableDatabase();
			
			ContentValues values = new ContentValues(); 
			values.put(PeridInfoEntry.COLUMN_NAME_PERIOD_NAME, name);
			
			return db.insert(PeridInfoEntry.TABLE_NAME, null, values);
		}
		catch(Exception ex)
		{
			Log.e(_LogTag,ex.getMessage());
		}
		return -1;
	}
	
	public List<PeriodInfo> GetAllPeriods(){
		List<PeriodInfo> results = new ArrayList<PeriodInfo>();
		try
		{		
			OvulatoryMonitorDbHelper mDbHelper = new OvulatoryMonitorDbHelper(_context);
			SQLiteDatabase db = mDbHelper.getReadableDatabase();
			
			String[] projection = { PeridInfoEntry.COLUMN_NAME_PERIOD_ID,
					PeridInfoEntry.COLUMN_NAME_PERIOD_NAME,
					PeridInfoEntry.COLUMN_NAME_PERIOD_STARTDATE };   
			
			Cursor cursor = db.query(PeridInfoEntry.TABLE_NAME,
					projection,                          
					null,                             
					null,                           
					null,                                     
					null,                                     
					null);
			
			while(cursor.moveToNext())
			{
				String id = cursor.getString(cursor.getColumnIndexOrThrow(PeridInfoEntry.COLUMN_NAME_PERIOD_ID) );
				String name = cursor.getString(cursor.getColumnIndexOrThrow(PeridInfoEntry.COLUMN_NAME_PERIOD_NAME));
				String startDate = cursor.getString(cursor.getColumnIndexOrThrow(PeridInfoEntry.COLUMN_NAME_PERIOD_STARTDATE));
				
				PeriodInfo info = new PeriodInfo();
				info.setId(id);
				info.setName(name);
				info.setStartDate(startDate);
				
				results.add(info);
			}
			
			if(cursor!= null)
			{
				if(!cursor.isClosed())
				{
					cursor.close();
				}
			}
		}
		catch(Exception ex)
		{
			Log.e(_LogTag,ex.getMessage());
		}
		
		return results;
	}
}
